package com.cherrish.demo.thread;

import java.util.concurrent.CyclicBarrier;

/**
 * @author cherrish
 * @time 2019-02-27 14:01
 * @name TestCyclicBarrier
 * @desc:
 */
public class TestCyclicBarrier {
    public static class WorkerThread implements Runnable {
        private final CyclicBarrier cyclicBarrier;
        public WorkerThread(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " pre-working");
                /**
                  * 线程在这里等待，直到所有线程都到达barrier。
                  */
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName() + " working");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_NUM = 5;
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_NUM, new Runnable() {
            /**
              * 当所有线程到达barrier时执行
              */
            @Override
            public void run() {
                System.out.println("--------------Inside Barrier--------------");
            }
        });

        for (int i = 0; i < THREAD_NUM; i++) {
            new Thread(new WorkerThread(cyclicBarrier)).start();
        }
    }
}
